//
//  RecoverPasswordViewModel.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/6/8.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift

class RecoverPasswordViewModel: NSObject {

    var valid:Observable<(Bool, String)>!
    var sendSms:Observable<Bool>!
    var setPwd:Observable<Bool>!
    var validMobile:Observable<Bool>!
    
    init(mobile:Observable<String>, code:Observable<String>, newPassword:Observable<String>, sendSmsTap:Observable<Void>, setTap:Observable<Void>) {
        
        validMobile = mobile.map { return $0.count == 11 }
                        .share(replay: 1)
        
        valid = Observable.combineLatest(mobile, code, newPassword) { strMobile, strCode, strNewPassword in
            let validMobile = strMobile.count == 11
            let validCode = !strCode.isEmpty
            let validNewPassword = strNewPassword.count >= minPasswordLength
            var strTips = ""
            if !validMobile && !strMobile.isEmpty {
                strTips = "请输入正确的手机号"
            } else if !validNewPassword && !strNewPassword.isEmpty {
                strTips = "密码至少需要\(minPasswordLength)位"
            }
            return (validMobile && validCode && validNewPassword, strTips)
        }.share(replay: 1)
        
        sendSms = sendSmsTap.withLatestFrom(mobile)
                    .flatMapLatest { strMobile -> Observable<Bool> in
                        return NetworkTool
                            .requestData(url: ActionURL.SEND_SMS, param: ["mobile":strMobile,"type":1])
                            .map({ (json) -> Bool in
                                return true
                            }).catchErrorJustReturn(false)
                            .observeOn(MainScheduler.instance)
                    }.share(replay: 1)
        
        let combine = Observable.combineLatest(mobile, code, newPassword) { (mobile:$0, code:$1, newPassword:$2) }.share(replay: 1)
        setPwd = setTap.withLatestFrom(combine)
                    .flatMapLatest { pair -> Observable<Bool> in
                        return NetworkTool
                            .requestData(url: ActionURL.RESET_PWD, param: ["mobile":pair.mobile,"verify":pair.code,"newpassword":pair.newPassword])
                            .map({ (json) -> Bool in
                                MainTools.makeToast(message: json["message"].stringValue)
                                return true
                            }).catchErrorJustReturn(false)
                            .observeOn(MainScheduler.instance)
                    }.share(replay: 1)
        
    }
    
}
